/*
 * @author Javier A. Ramírez M.
 * jaramirez85@yahoo.es
 */

package com.jav.per;


import com.jav.inter.Constantes;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

public class Persistencia implements Constantes{

    private String rmsName;
    private RecordStore recordStore;
    private boolean open = false;

    public Persistencia(String rmsName) throws Exception {
        this.rmsName = rmsName;
        open();
    }

    public void open() throws Exception {
        try {
            this.recordStore = RecordStore.openRecordStore(this.rmsName,true);
            open = true;
        }
        catch (Exception e) {
            throw new Exception(this.rmsName+"::open::"+e);
        }
    }

    public void close() throws Exception {
        if (this.recordStore != null) {
            try {
                this.recordStore.closeRecordStore();
                open = false;
            } catch(Exception e) {
                throw new Exception(this.rmsName+"::close::"+e);
            }
        }
    }

    public static void delete(String rms) throws RecordStoreException{
        RecordStore.deleteRecordStore(rms);
    }

    public RecordStore getRecordStore() {
        return this.recordStore;
    }
    public String getRMSName() {
        return this.rmsName;
    }

    public void save(byte []by) throws Exception {

        try{
            if ((getRMSName().equals(PERS_RUTA) || getRMSName().equals(PERS_LICENCIA) ||  getRMSName().equals(PERS_DATA_SERVER)) && getRecordStore().getNumRecords() > 0){
                    getRecordStore().closeRecordStore();
                    RecordStore.deleteRecordStore(rmsName);
                    this.open();
            }
            getRecordStore().addRecord(by, 0, by.length);
            
            
        }
        finally{
            close();
        }


    }

}
